import 'package:flutter/widgets.dart';

/// Animates the rotation of a widget when [turns]  is changed.

class TurnBox extends StatefulWidget {
  TurnBox(
    double turns,
    int speed,
    Widget child
  ) {
    this.turns=turns;
    this.speed=speed;
    this.child=child;
  }

  /// Controls the rotation of the child.
  ///
  /// If the current value of the turns is v, the child will be
  /// rotated v * 2 * pi radians before being painted.
  double turns=0.2;

  /// Animation duration in milliseconds
  int speed=200;

  late Widget child;

  @override
  _TurnBoxState createState() => new _TurnBoxState();
}

class _TurnBoxState extends State<TurnBox>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
        vsync: this,
        lowerBound: -double.infinity,
        upperBound: double.infinity
    );
    _controller.value = widget.turns;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RotationTransition(
      turns: _controller,
      child: widget.child,
    );
  }

  @override
  void didUpdateWidget(TurnBox oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.turns != widget.turns) {
      _controller.animateTo(
          widget.turns,
          duration: Duration(milliseconds: widget.speed??200),
          curve: Curves.easeOut,
      );
    }
  }
}